# src/query_manager.py

import json
import logging
import os

from config.config_manager import OUTPUT_DIR


def query_by_message_id(message_id):
    """
    根据 MessageId 查询文件路径（支持跨日期查询）
    """
    try:
        # 获取所有日期文件夹
        date_folders = [d for d in os.listdir(OUTPUT_DIR) if os.path.isdir(os.path.join(OUTPUT_DIR, d))]

        # 遍历所有日期文件夹
        files_info = []  # 用于存储文件路径和内容的列表
        for date_folder in date_folders:
            target_dir = os.path.join(OUTPUT_DIR, date_folder, message_id)
            if os.path.exists(target_dir) and os.path.isdir(target_dir):
                files = os.listdir(target_dir)
                for file in files:
                    file_path = os.path.join(target_dir, file)
                    if os.path.isfile(file_path):
                        # 读取文件内容
                        with open(file_path, 'r', encoding='utf-8') as file:
                            content = file.read()
                        # 将文件路径和内容添加到列表中
                        files_info.append({
                            "file_path": file_path,
                            "file_content": content
                        })

        if files_info:
            response = {
                "message_id": message_id,
                "files": files_info,
                "status": "success",
                "error": ""
            }
        else:
            response = {
                "message_id": message_id,
                "files": [],
                "status": "failed",
                "error": f"未找到 MessageId 为 {message_id} 的文件"
            }
    except Exception as e:
        logging.error(f"查询 MessageId '{message_id}' 时出错: {e}")
        response = {
            "message_id": message_id,
            "files": [],
            "status": "failed",
            "error": str(e)
        }

    # 将字典转换为 JSON 格式的字符串
    return json.dumps(response, ensure_ascii=False)  # 确保中文正常显示
